package com.mlh.runner;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mlh.entity.Article;
import com.mlh.mapper.ArticleMapper;
import com.mlh.service.ArticleService;
import com.mlh.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 缪林辉
 * @date 2024/3/17 11:45
 * @DESCRIPTION
 */
@Component
public class ViewCountRunner implements CommandLineRunner {

    //该方法是在ioc初始化完毕后执行的
    //意味着可以使用容器中的对象
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private RedisCache redisCache;
    @Override
    public void run(String... args) throws Exception {
        //自己的写法
        // //把ViewCount数据从数据库中取出  对应文章id和ViewCount
        // LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
        // queryWrapper.select(Article::getId,Article::getViewCount);
        // List<Article> list = articleService.list(queryWrapper);
        // for (Article article : list) {
        //     // 把获取出来的数据存入到redis中
        //     redisCache.setCacheObject("articleId:"+article.getId(),article.getViewCount());
        // }

        //查询博客信息 id viewCount
        List<Article> articles = articleMapper.selectList(null);
        //这里直接收集成 map<id,viewCount>
        Map<String, Integer> viewCountMap = articles.stream()
                //ViewCount原本是long类型的 这里要转成integer类型
                //因为redis中 long类型的数据是  1L  带L的  没办法实现自增
                .collect(Collectors.toMap(article -> article.getId().toString(),
                        article ->  article.getViewCount().intValue()));
        //存储到redis中
        redisCache.setCacheMap("article:viewCount",viewCountMap);

        //查看redis中是否存储成功
        // Map<String, Object> cacheMap = redisCache.getCacheMap("article:viewCount");
        // System.out.println(cacheMap);
    }
}
